package com.freeman.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.xml.bind.DatatypeConverter;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;

public class HttpBasicAuthUtil {
	
	public static void main(String[] args) throws Throwable {
		//String s= HttpBasicAuthUtil.doGet("http://localhost:8088/activiti-rest/service/repository/deployments", "kermit",  "kermit");
		//String s1= HttpBasicAuthUtil.doGet("http://localhost:8088/activiti-rest/service/rutime/tasks", "kermit",  "kermit");
		//String s2= HttpBasicAuthUtil.doPost("http://localhost:8088/activiti-rest/service/query/tasks", "kermit",  "kermit");
		
		//Tomcat Web Application Manager
		String s2= HttpBasicAuthUtil.doGet("http://localhost:8080/manager/html/", "tomcat",  "tomcat");
		System.out.println(s2);
	}
	
	
	
	public static String readFile(String path) throws IOException {
         File file=new File(path);
         if(!file.exists()||file.isDirectory())
             throw new FileNotFoundException();
         FileInputStream fis=new FileInputStream(file);
         byte[] buf = new byte[1024];
         StringBuffer sb=new StringBuffer();
         while((fis.read(buf))!=-1) {
             sb.append(new String(buf));    
             buf=new byte[1024];//重新生成，避免和上次读取的数据重复
         }
         return sb.toString();
    }
	  
	public static String doPost(String url,String user,String passwd,String jsonData) {
	    try {
	        //DefaultHttpClient Client = new DefaultHttpClient();
	        CloseableHttpClient httpclient = HttpClients.createDefault();

	        //String s="http://localhost:8088/activiti-rest/service/repository/deployments";
	        HttpPost httpPost = new HttpPost(url);
	        String encoding = DatatypeConverter.printBase64Binary((user+":"+passwd).getBytes("UTF-8"));
	        httpPost.setHeader("Authorization", "Basic " + encoding);
	        httpPost.addHeader(HTTP.CONTENT_TYPE, HTTP.UTF_8);
	        httpPost.addHeader(HTTP.CONTENT_TYPE,"application/json");
	        StringEntity params =new StringEntity(jsonData,"UTF-8");
	        //List<NameValuePair> list=URLEncodedUtils.parse(params);
	        //System.out.println(URLEncodedUtils.format(list, HTTP.UTF_8);//输出结果为空
	        httpPost.setEntity(params);
	        
	        CloseableHttpResponse  response = httpclient.execute(httpPost);

	        System.out.println("response = " + response);

	        BufferedReader breader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
	        StringBuilder responseString = new StringBuilder();
	        String line = "";
	        while ((line = breader.readLine()) != null) {
	            responseString.append(line);
	        }
	        breader.close();
	        String repsonseStr = responseString.toString();
	        
	        System.out.println("repsonseStr = " + repsonseStr);
	        return repsonseStr;
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	    return null;
	}
	public static String doGet(String url,String user,String passwd) throws Throwable {
	    try {
	        //DefaultHttpClient Client = new DefaultHttpClient();
	        CloseableHttpClient httpclient = HttpClients.createDefault();

	        //String s="http://localhost:8088/activiti-rest/service/repository/deployments";
	        HttpGet httpGet = new HttpGet(url);
	        sun.misc.BASE64Encoder en=new sun.misc.BASE64Encoder();
	        String encoding =en.encode((user+":"+passwd).getBytes("UTF-8"));
	        //String encoding = DatatypeConverter.printBase64Binary((user+":"+passwd).getBytes("UTF-8"));
	        httpGet.setHeader("Authorization", "Basic " + encoding);
	        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(500).setConnectTimeout(500).build();//设置请求和传输超时时间
	        httpGet.setConfig(requestConfig);
	        CloseableHttpResponse  response = httpclient.execute(httpGet);

	        //System.out.println("response 中文1= " + response);

	        BufferedReader breader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
	        StringBuilder responseString = new StringBuilder();
	        String line = "";
	        while ((line = breader.readLine()) != null) {
	            responseString.append(line);
	        }
	        breader.close();
	        String repsonseStr = responseString.toString();
	        
	        //System.out.println("repsonseStr中文2 = " + repsonseStr);
	        return repsonseStr;
	    } catch (Throwable e) {
	        //e.printStackTrace();
	    	throw e;
	    }
	    //return null;
	}
}
